import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { DAOAnalysis } from '../src/utils/dao-analysis';

/**
 * DAO关联检查脚本
 * 用于验证所有DAO之间的关联关系和数据一致性
 */
async function runDAORelationshipCheck() {
  let mongoServer: MongoMemoryServer | null = null;
  
  try {
    console.log('🚀 开始DAO关联检查...');
    
    // 启动内存数据库
    mongoServer = await MongoMemoryServer.create();
    const mongoUri = mongoServer.getUri();
    
    // 连接数据库
    await mongoose.connect(mongoUri);
    console.log('✅ 内存数据库连接成功');
    
    // 创建分析实例
    const daoAnalysis = new DAOAnalysis();
    
    // 检查DAO关联关系
    console.log('\n📊 检查DAO关联关系...');
    const relationshipResult = await daoAnalysis.checkDAORelationships();
    
    console.log('\n=== DAO关联关系分析结果 ===');
    console.log(`总关联关系数: ${relationshipResult.summary.totalRelationships}`);
    console.log(`有效关联关系: ${relationshipResult.summary.validRelationships}`);
    console.log(`无效关联关系: ${relationshipResult.summary.invalidRelationships}`);
    console.log(`覆盖率: ${relationshipResult.summary.coverage}%`);
    
    // 显示详细关联关系
    console.log('\n=== 详细关联关系 ===');
    relationshipResult.relationships.forEach((rel, index) => {
      const status = rel.isValid ? '✅' : '❌';
      console.log(`${index + 1}. ${status} ${rel.source} -> ${rel.target} (${rel.type})`);
      console.log(`   描述: ${rel.description}`);
      if (rel.errors && rel.errors.length > 0) {
        console.log(`   错误: ${rel.errors.join(', ')}`);
      }
    });
    
    // 分析测试覆盖率
    console.log('\n📈 分析测试覆盖率...');
    const coverageResult = await daoAnalysis.analyzeTestCoverage();
    
    console.log('\n=== 测试覆盖率分析结果 ===');
    console.log(`总DAO数: ${coverageResult.summary.totalDAOs}`);
    console.log(`总方法数: ${coverageResult.summary.totalMethods}`);
    console.log(`已测试方法数: ${coverageResult.summary.testedMethods}`);
    console.log(`总体覆盖率: ${coverageResult.summary.overallCoverage}%`);
    
    // 显示每个DAO的覆盖率
    console.log('\n=== 各DAO覆盖率详情 ===');
    coverageResult.daos.forEach((dao, index) => {
      console.log(`${index + 1}. ${dao.name}: ${dao.overallCoverage}% (${dao.methods.length}个方法)`);
      
      // 显示覆盖率较低的方法
      const lowCoverageMethods = dao.methods.filter(method => method.coverage < 80);
      if (lowCoverageMethods.length > 0) {
        console.log(`   ⚠️  低覆盖率方法:`);
        lowCoverageMethods.forEach(method => {
          console.log(`      - ${method.name}: ${method.coverage}% (${method.testCases}个测试用例)`);
        });
      }
    });
    
    // 生成完整报告
    console.log('\n📋 生成完整分析报告...');
    const fullReport = await daoAnalysis.generateAnalysisReport();
    
    console.log('\n=== 改进建议 ===');
    fullReport.recommendations.forEach((recommendation, index) => {
      console.log(`${index + 1}. ${recommendation}`);
    });
    
    // 保存报告到文件
    const reportPath = './dao-analysis-report.json';
    const fs = require('fs');
    fs.writeFileSync(reportPath, JSON.stringify(fullReport, null, 2));
    console.log(`\n💾 完整报告已保存到: ${reportPath}`);
    
    // 检查是否有需要关注的问题
    const hasIssues = relationshipResult.summary.invalidRelationships > 0 || 
                     coverageResult.summary.overallCoverage < 80;
    
    if (hasIssues) {
      console.log('\n⚠️  发现需要关注的问题:');
      if (relationshipResult.summary.invalidRelationships > 0) {
        console.log(`   - 有 ${relationshipResult.summary.invalidRelationships} 个无效的关联关系`);
      }
      if (coverageResult.summary.overallCoverage < 80) {
        console.log(`   - 总体测试覆盖率 ${coverageResult.summary.overallCoverage}% 低于建议的80%`);
      }
    } else {
      console.log('\n🎉 所有检查通过！DAO关联关系和测试覆盖率都符合要求。');
    }
    
  } catch (error) {
    console.error('❌ DAO关联检查失败:', error);
    process.exit(1);
  } finally {
    // 断开数据库连接
    if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
    }
    
    // 停止内存数据库
    if (mongoServer) {
      await mongoServer.stop();
    }
    
    console.log('\n✅ 数据库连接已断开');
    process.exit(0);
  }
}

// 运行检查
if (require.main === module) {
  runDAORelationshipCheck();
}

export { runDAORelationshipCheck };